<template>

	<view class="BaiDuMap">
		<ibalbal-tabbar :active="1" @changeActiveIndex="changeActiveIndex" :config="iconConfig"></ibalbal-tabbar>

		<view class="page" v-if="cha">
			<view class="action">
				<view>
					<image src="/static/center4/setting.png"></image>
				</view>
			</view>
			<view class="user">
				<image class="avatar" src="/static/center4/avatar.png"></image>
				<view class="name">
					<text>{{this.showID}}</text>
					<text>{{this.showType}}</text>
				</view>
				<image class="right" src="/static/center4/right.png"></image>
			</view>

			<view class="card">
				<view class="menu">
					<view class="item2" v-for="v in menus1" :key="v.id" @click="handleItemClick(v.id)">
						<image :src="v.icon"></image>
						<view>{{v.name}}</view>
						<image class="arrow" v-if="v.arrow" src="/static/center1/right.png"></image>
					</view>
				</view>
			</view>
		</view>


		<view class="BaiDuMap" v-else>
			<baidu-map :center="center" :zoom="zoom" :scroll-wheel-zoom="true" style="width: 100%; height: 100%"
				@ready="handler" @click="getClickInfo" @moving="syncCenterAndZoom" @moveend="syncCenterAndZoom"
				@zoomend="syncCenterAndZoom" :min-zoom=5>
				<!-- 必须给容器指高度，不然地图将显示在一个高度为0的容器中，看不到 -->

				<view class="item" v-show="lineShow&&!show2">
					<next-bubble-menu :d-width="200" :dataList="dataList" bingEleId="test1" :relativeAllow="-30"
						@change="handleMenuChange">
						<view id="test1" class="flex-line">
							<text>选择线路</text>
						</view>
					</next-bubble-menu>
				</view>

				<view class="btn-win"><wyb-button class="btn" width="360rpx" type="filled" @click="findLocation()">
						<text class="button-text">{{textWithout}}</text></wyb-button>
				</view>



				<fui-toast ref="toast"></fui-toast>



				<bm-navigation anchor="BMAP_ANCHOR_TOP_RIGHT"></bm-navigation>

				<div>
					<bm-marker v-for="(marker, index) in carStations" :key="index" @click="showPopup(index)"
						:position="{lng: marker.stationLng, lat: marker.stationLat}" :dragging="false">
						<bm-label :content="marker.stationName" :labelStyle="{color: 'red', fontSize : '15px'}"
							:offset="labelOffset[index]" />
					</bm-marker>
				</div>

				<div>
					<!-- 显示车辆当前位置 -->
					<bm-marker v-for="(marker, vindex) in carLocation" :key="vindex" @click="showPopup2(vindex)"
						:position="{lng: marker.carLng, lat: marker.carLat}" :dragging="false"
						:icon="{url: require('@/static/img/校车 (2).png'), size: {width: 32, height: 32}}">
					</bm-marker>
				</div>

				<div>
					<!-- 显示人当前位置 -->
					<bm-marker :position="{lng: autoLocationCenter.lng, lat: autoLocationCenter.lat}"
						:icon="{url: 'http://developer.baidu.com/map/jsdemo/img/fox.gif', size: {width: 300, height: 157}}">
					</bm-marker>
				</div>

				<fui-top-popup :show="show2" @close="closePopup(2)">
					<view class="fui-popup__container">
						<view class="fui-btn__box"></view> <!-- //占位 -->
						<text>Name: {{this.showCarInfo.driverName}}</text>
						<text>DriverId:{{this.showCarInfo.driverId}}</text>
						<text>WorkingInterval:{{this.showCarInfo.workingInterval}}{{this.showCarInfo.workingTime}}</text>

						<view class="fui-btn__box">
							<fui-button type="gray" width="240rpx" height="80rpx" text="取消" :margin="['0','16rpx']"
								@click="closePopup(2)">
							</fui-button>
							<fui-button width="240rpx" height="80rpx" text="已经上车" :margin="['0','16rpx']"
								@click="lastFunction()"></fui-button>
						</view>
					</view>
				</fui-top-popup>

				<fui-bottom-popup :show="show" @close="closePopup(1)">
					<view class="fui-popup__container">
						<text class="fui-title">{{StationName}}</text>
						<view>
							<!-- 轮播图 -->
							<swiper class="my-swiper" indicator-dots="true" autoplay="true" interval="3000"
								circular="true">
								<swiper-item>
									<!-- 使用网络图片 -->
									<image
										src="https://img.alicdn.com/imgextra/i1/6000000006674/O1CN01a2DKMD1zAkGT6zoMf_!!6000000006674-0-octopus.jpg"
										class="slide-image"></image>
								</swiper-item>
								<swiper-item>
									<!-- 使用网络图片 -->
									<image
										src="https://img.alicdn.com/imgextra/i4/6000000002919/O1CN01aNIoQx1XQx2RZ9xm1_!!6000000002919-0-octopus.jpg"
										class="slide-image"></image>
								</swiper-item>
								<swiper-item>
									<!-- 使用网络图片 -->
									<image
										src="https://img.alicdn.com/imgextra/i1/6000000002349/O1CN01I4vVaI1TDtHY74PVb_!!6000000002349-0-octopus.jpg"
										class="slide-image"></image>
								</swiper-item>
							</swiper>

							<!-- 介绍文本 -->
							<view class="fui-descr">
								{{StationIntroduce}}
							</view>
							<view>
								<view class="fui-btn__box">
									<fui-button width="240rpx" height="80rpx" @click="getHereClick()" text="到这儿去"
										:margin="['0','16rpx']"></fui-button>
									<fui-button type="gray" width="240rpx" @click="showCarLine()" height="80rpx"
										text="站点经车" :margin="['0','16rpx']"></fui-button>
								</view>
							</view>
							<view class="fui-btn__box"></view>
						</view>

						<view class="fui-icon__close" @tap="closePopup(1)">
							<fui-icon name="close" :size="48"></fui-icon>
						</view>

						<!-- 介绍 -->
					</view>
				</fui-bottom-popup>

				<div v-if="shouldWalk">
					<bm-walking :start="{lng: walkStart.lng, lat: walkStart.lat}"
						:end="{lng: walkEnd.lng, lat: walkEnd.lat}"></bm-walking>
				</div>

				<div v-if="dataLoad">
					<bm-driving :start="convertToLocation(this.carInfo[this.nowCarLine][0].startStation)"
						:end="convertToLocation(this.carInfo[this.nowCarLine][0].endStation)" location="南宁"
						:waypoints="this.waypoints"></bm-driving>
				</div>


			</baidu-map>
		</view>
	</view>

</template>
<script>
	// import fuiButton from "@/components/firstui/fui-button/fui-button"
	import {
		setInterval
	} from 'timers';
	import haversine from 'haversine'
	import {
		constrainedMemory
	} from 'process';
	export default {
		// components: {
		//  fuiButton
		// },
		data() {
			return {
				menus1: [{
						id: 1,
						name: '我的订单',
						icon: '/static/center4/book.png',
						arrow: true
					},
					{
						id: 2,
						name: '我的评价',
						icon: '/static/center4/kefu.png',
						arrow: true
					},
				],
				textWithout: "查看当前位置",
				showID: 123345,
				showType: "学生",
				cha: false,
				active: 0,
				iconConfig: [{
					icon: "icon-gps_o",
					name: "应用"
				}, {
					icon: "icon-my",
					name: "我的"
				}],
				// 地址信息
				dataLoad: false, //是否显示车辆路线
				show: false, //显示下面的窗口
				show2: false,
				carInfo: [], //当前线路经过车的信息
				showCarInfo: [], //当前要显示在界面上车辆的信息
				carLocation: [], //实时显示校车位置
				carStations: [], //车站的全部信息
				nearestStation: [], //距离当前人物最近的车站
				choseLineString: null,
				choseLine: [],
				waypoints: [],
				nowLine: -1,
				nowCarLine: 'carLine',
				center: {
					lng: 0,
					lat: 0,
				},
				autoLocationCenter: {
					lng: 108.297348,
					lat: 22.846808,
				},
				walkStart: {
					lng: 0,
					lat: 0,
				},
				walkEnd: {
					lng: 0,
					lat: 0,
				},
				choseLocation: {
					lng: 0,
					lat: 0,
				},
				shouldWalk: false,
				lineShow: false,
				//地图展示级别
				zoom: 18,
				StationName: "测试标题一",
				StationIntroduce: "这里是您的介绍文本，可以详细描述轮播图中展示的内容或其他相关信息。",
				dataList: [{
						text: '测试一',
					},
					{
						text: '测试二',
					},
					{
						text: '测试三',
						iconSrc: 'https://i-1.lanrentuku.com/2020/10/27/73be0f11-4027-4e5c-8f8f-be31fa4d2834.png?imageView2/2/w/500'
					}
				],
			};
		},
		computed: {
			labelOffset() {
				return this.carStations.map(marker => {
					const labelWidth = marker.stationName.length * 11; // 假设每个字符宽度为15px
					return {
						width: -labelWidth / 2,
						height: 30
					}; // 根据字体长度计算偏移量
				});
			}
		},
		mounted() {
			setInterval(() => {
				//this.getLocation();
			}, 5000);

			setInterval(() => {
				this.getCarLocation();
			}, 2000);
			if (this.$store.state.hasLogin == true) {
				this.showID = this.$store.state.userdata[1];
				console.log("inhereCh");
			}
		}, //http://127.0.0.1:4523/m1/3961673-0-default/car/line?lineId=1
		onLoad() {
			uni.request({
				url: 'http://localhost:8080/app/car/station',
				// url: 'http://127.0.0.1:4523/m1/3961673-0-default/map/palceList',
				method: 'GET',
				success: res => {
					if (res.statusCode === 200 && res.data.code === 0) {
						this.carStations = res.data.carStation;
						console.log("成功");
						console.log(this.$store.state.userdata)
					} else {
						console.log('请求失败');
					}
				},
				fail: err => {
					console.log('请求失败', err);
				}
			});
		},
		methods: {
			lastFunction() {
				uni.request({
					url: 'http://localhost:8080/app/order/newOrder?uid=' + this.showID +
						'&driveId=' + this.showCarInfo.driverId + '&peopleLat=' + this.autoLocationCenter.lat +
						'&peopleLng=' + this.autoLocationCenter.lng,
					method: 'GET',
					success: res => {
						if (res.statusCode === 200 && res.data.code === 0) {
							let options = {}
							options.text = '付款成功';
							this.$refs.toast.show(options);
							this.closePopup(2);
						} else {
							console.log('请求失败');
							let options = {}
							options.text = '距离车辆太远';
							this.$refs.toast.show(options);
							this.closePopup(2);
						}
					},
					fail: err => {
						console.log('请求失败', err);
					}
				});
			},
			handleItemClick(menuItem) {
				switch (menuItem) {
					case 1:
						uni.navigateTo({
							url: '/pages/order/stu', // 使用绝对路径
						});
						break;
					case 2:
						uni.navigateTo({
							url: '/pages/order/stuEvaluate', // 使用绝对路径
						});
						break;
					default:
						break;
				}
			},
			showPopup2(type) {
				let j = 'carInfo' + this.nowLine;
				for (let key in this.carInfo[j]) {
					if (this.carInfo[j][key].carId == this.carLocation[type].carId) {
						this.showCarInfo = this.carInfo[j][key].driverInfoEntity;
						console.log('111');
						console.log(this.showCarInfo);
					}
					//console.log(this.carInfo[j][key]);
				}
				this.show2 = true;
			},
			getCarLocation() {
				if (this.lineShow) {
					uni.request({
						url: 'http://localhost:8080/app/car/carLocation?lineId=' + this.nowLine,
						// url: 'http://127.0.0.1:4523/m1/3961673-0-default/map/palceList',
						method: 'GET',
						success: res => {
							if (res.statusCode === 200 && res.data.code === 0) {
								this.carLocation = res.data.carLocation;

							} else {
								console.log('请求失败');

							}
						},
						fail: err => {
							console.log('请求失败', err);
						}
					});
				}
			},
			convertToLocation(str) {
				let a = str.split(', ');
				let b = a[0].split(':');
				let c = a[1].split(':');
				// console.log(c[1]);
				return {
					lng: parseFloat(b[1]),
					lat: parseFloat(c[1])
				};
			},
			changeLine() {
				this.waypoints = [];
				this.dataLoad = false;
				this.nowCarLine = 'carLine';
				this.nowCarLine += this.nowLine;
				for (let key in this.carInfo[this.nowCarLine][0]) {
					if (key.startsWith('passStation')) {
						if (this.carInfo[this.nowCarLine][0][key] !== "null") {
							// console.log(carInfo[key]);
							let coords = this.carInfo[this.nowCarLine][0][key].split(', ');
							let alng = coords[0].split(':')[1];
							let alat = coords[1].split(':')[1];
							this.waypoints.push({
								lng: alng,
								lat: alat
							});
						}
					}
				}
				this.dataLoad = true;
			},
			handleMenuChange(item) {
				if (item.text != '关闭站点') {

					for (let i = 0; i < this.choseLine.length; i++) {
						this.dataList[i].iconSrc = '';
					}
					item.iconSrc =
						'https://i-1.lanrentuku.com/2020/10/27/73be0f11-4027-4e5c-8f8f-be31fa4d2834.png?imageView2/2/w/500';
					// 在这里处理菜单点击事件

					this.nowLine = item.line;
					this.changeLine();
				} else {
					this.dataLoad = false;
					this.lineShow = false;
					this.shouldWalk = false;
				}

				// console.log(this.nowLine);
			},
			getLineInfo(callback) {
				uni.request({
					url: 'http://localhost:8080/app/car/line?lineString=' + this.choseLineString,
					method: 'GET',
					success: res => {
						if (res.statusCode === 200 && res.data.code === 0) {
							this.carInfo = res.data.result;
							if (typeof callback === 'function') {
								callback();
							}
						} else {
							console.log('请求失败');
						}
					},
					fail: err => {
						console.log('请求失败', err);
					}
				});
			},
			showCarLine() { //展示线路
				this.show = false;
				this.lineShow = true;
				let options = {}
				options.text = '已展示站点线路';
				this.$refs.toast.show(options);
				this.dataLoad = true;
			},
			getHereClick() {
				this.lineShow = true;
				this.show = false;
				this.nearestStation = [];
				this.walkStart = this.autoLocationCenter;
				this.center = this.autoLocationCenter; //切换地图位置

				//本来想和驾车同时实现，但是不太行
				let walkDistance = haversine({
					latitude: this.walkStart.lat,
					longitude: this.walkStart.lng
				}, {
					latitude: this.choseLocation.lat,
					longitude: this.choseLocation.lng,
				})
				console.log(walkDistance);
				let minDistance = Infinity;
				let neaAAA = ({
					lng: 9999,
					lat: 9999,
					lineId: -1,
				});
				for (let i = 0; i < this.choseLine.length; i++) {
					let j = 'carLine' + this.choseLine[i];

					let calculate = ({
						lng: 109,
						lat: 109,
						lineId: -1,
					});
					// console.log(this.carInfo[j][0])
					for (let key in this.carInfo[j][0]) {
						calculate.lineId = this.carInfo[j][0]["lineId"];
						if (this.carInfo[j][0][key] != "null" &&
							key != "lineId") {
							let coords = this.carInfo[j][0][key].split(', ');
							let alng = coords[0].split(':')[1];
							let alat = coords[1].split(':')[1];
							calculate.lng = alng;
							calculate.lat = alat;

							let lineDistance = haversine({
								latitude: this.walkStart.lat,
								longitude: this.walkStart.lng
							}, {
								latitude: calculate.lat,
								longitude: calculate.lng,
							})
							// console.log(lineDistance);
							// console.log(minDistance);

							if (lineDistance < minDistance) {
								neaAAA.lat = calculate.lat;
								neaAAA.lng = calculate.lng;
								neaAAA.lineId = calculate.lineId;
								minDistance = lineDistance;
								// console.log(neaAAA);
								// console.log(minDistance);
							}
							// console.log(neaAAA);
							// console.log(minDistance);
						}
					}

					// console.log(neaAAA);
					// console.log(minDistance);
					if (minDistance < walkDistance) {
						this.nearestStation.push(neaAAA);
					}

				}
				let options = {}
				// console.log(this.nearestStation);
				if (this.nearestStation.length == 0) {
					this.walkEnd.lat = this.choseLocation.lat;
					this.walkEnd.lng = this.choseLocation.lng;
					options.text = '步行最佳，请步行至终点';
				} else {
					this.walkEnd.lat = this.nearestStation[0].lat;
					this.walkEnd.lng = this.nearestStation[0].lng;
					options.text = '请步行至终点，在终点处上' + this.nearestStation[0].lineId +
						'号站点车';
					// this.dataLoad = true;
				}
				this.shouldWalk = true;
				this.$refs.toast.show(options);

			},
			getLocation() { //获得现在位置
				const that = this;
				var geolocation = new BMap.Geolocation();
				geolocation.getCurrentPosition(function(r) {
					if (this.getStatus() == BMAP_STATUS_SUCCESS) {
						that.autoLocationCenter.lng = r.longitude;
						that.autoLocationCenter.lat = r.latitude;
						console.log(that.autoLocationCenter);
					} else {
						alert("failed" + this.getStatus());
					}
				});
			},
			findLocation() { //获得现在位置
				this.center = this.autoLocationCenter;
				let tabBarOptions = {
					index: 0, //要修改的下标
					text: 'a', //文字
					iconPath: "static/tabbar/地图_定位_o (1).png",
					selectedIconPath: "static/tabbar/地图_定位_o.png",
					pagePath: "pages/map/map",
				};
				//uniapp的api，传入上面写好的对象
				uni.setTabBarItem(tabBarOptions);

			},
			showPopup(type) { //点击一个地点
				this.shouldWalk = false;
				this.dataLoad = false;
				this.lineShow = false;
				this.show = true;
				if (this.StationName != this.carStations[type].stationName) {
					this.nowCarLine = 'carLine';
					this.waypoints = [];
					this.dataList = [];
					this.choseLocation.lat = this.carStations[type].stationLat;
					this.choseLocation.lng = this.carStations[type].stationLng;
					this.StationName = this.carStations[type].stationName;
					this.StationIntroduce = this.carStations[type].introduce;
					this.choseLineString = this.carStations[type].linePass;
					let choseLineArray = this.choseLineString.split(',');
					this.choseLine = choseLineArray.map(item => parseInt(item));
					this.nowLine = this.choseLine[0];
					this.dataList.push({
						text: '线路' + this.nowLine,
						iconSrc: 'https://i-1.lanrentuku.com/2020/10/27/73be0f11-4027-4e5c-8f8f-be31fa4d2834.png?imageView2/2/w/500',
						line: this.nowLine,
					});
					for (let i = 1; i < this.choseLine.length; i++) {
						this.dataList.push({
							text: '线路' + this.choseLine[i],
							iconSrc: '',
							line: this.choseLine[i],
						});
					}
					this.dataList.push({
						text: '关闭站点'
					});
					this.getLineInfo(() => {
						// console.log(this.carInfo['carLine2'][0]);
						this.nowCarLine += this.nowLine;
						// console.log(this.nowCarLine);
						for (let key in this.carInfo[this.nowCarLine][0]) {
							if (key.startsWith('passStation')) {
								if (this.carInfo[this.nowCarLine][0][key] !== "null") {
									// console.log(carInfo[key]);
									let coords = this.carInfo[this.nowCarLine][0][key].split(', ');
									let alng = coords[0].split(':')[1];
									let alat = coords[1].split(':')[1];
									this.waypoints.push({
										lng: alng,
										lat: alat
									});
								}
							}
						}

					});
				} else {
					console.log("noin");
				}
			},
			closePopup(type) {
				if (type == 1) {
					this.show = false;
				} else {
					this.show2 = false;
				}

			},
			handler({
				BMap,
				map
			}) {
				this.zoom = this.zoom;
				const that = this;
				var geolocation = new BMap.Geolocation();
				geolocation.getCurrentPosition(function(r) {
					if (this.getStatus() == BMAP_STATUS_SUCCESS) {
						that.center.lng = r.longitude;
						that.center.lat = r.latitude;
						// console.log(that.center);
						this.autoLocationCenter = that.center;
					} else {
						alert("failed" + this.getStatus());
					}
				});
			},
			getClickInfo(e) {
				// 创建地理编码实例
				// const myGeo = new BMap.Geocoder();
				// // 根据坐标逆解析地址
				// myGeo.getLocation(new BMap.Point(e.point.lng, e.point.lat), (result) => {
				// 	console.log(result, "result-->>>>");
				// 	if (result) {
				// 		this.address = result.address;
				// 	}
				// });
				// this.center.lng = e.point.lng;
				// this.center.lat = e.point.lat;
			},
			syncCenterAndZoom(e) {
				// console.log('mytttt');
				console.log(e.target, 'e.target-->>>>')
				const {
					lng,
					lat
				} = e.target.getCenter();
				this.zoom = e.target.getZoom();
				this.center = e.target.getCenter();
			},
			changeActiveIndex(index) {
				if (index == 2) this.cha = true;
				else this.cha = false;

				console.log(this.cha)
			},
		},
	};
</script>

<style scoped lang="scss">
	.page {
		background: #f5f5f5;
		min-height: 100vh;

		.action {
			display: flex;
			justify-content: flex-end;
			padding: 10rpx;
			background: #fff;

			view {
				padding: 10rpx;
				margin: 0 10rpx;
				border-radius: 8rpx;
				width: 45rpx;
				height: 45rpx;

				&:active {
					background: #ccc;
				}

				image {
					width: 45rpx;
					height: 45rpx;
				}
			}
		}

		.user {
			display: flex;
			align-items: center;
			padding: 25rpx;
			background: #fff;

			&:active {
				background: #f0f0f0;
			}

			.avatar {
				width: 90rpx;
				height: 90rpx;
				border-radius: 50%;
			}

			.right {
				width: 30rpx;
				height: 30rpx;
			}

			.name {
				flex-grow: 1;
				display: flex;
				flex-direction: column;
				padding-left: 20rpx;

				text {
					&:nth-child(1) {
						font-size: 16px;
						font-weight: bold;
					}

					&:nth-child(2) {
						font-size: 12px;
						color: #777;
					}
				}
			}
		}

		.tip {
			background: #4776EC;
			width: 700rpx;
			margin: auto;
			height: 100rpx;
			border-radius: 12rpx;
			margin-top: 20rpx;
			display: flex;
			justify-content: space-between;
			align-items: center;
			color: #fff;

			view {
				padding-left: 20rpx;
				width: 330rpx;

				text {
					font-size: 14px;

					&:nth-child(2) {
						font-size: 16px;
						font-weight: bold;
						margin-left: 10rpx;
					}
				}
			}
		}

		.card {
			background: #fff;
			box-sizing: border-box;
			width: 700rpx;
			margin: auto;
			padding: 15rpx;
			margin-top: 20rpx;
			border-radius: 12rpx;

			.menu {

				.item2 {
					display: flex;
					height: 100rpx;
					align-items: center;
					padding: 0 20rpx;
					box-sizing: border-box;
					width: 700rpx;

					&:active {
						background: #f0f0f0;
					}

					image {
						height: 45rpx;
						width: 45rpx;
					}

					view {
						font-size: 14px;
						color: #444;
						padding-left: 15rpx;
						box-sizing: border-box;
						width: calc(100% - 100rpx);
					}

					.arrow {
						width: 26rpx;
						height: 26rpx;
					}
				}
			}
		}

	}

	@import url("./css/map.css");
</style>